package Test;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class FloatTest {

    public static void main(String[] args) {
        byte[] bytes = {(byte) 16, (byte) 8, (byte) 128, (byte) 6, (byte) 32, (byte) 26};
        for (int i = 0; i < bytes.length; i++) {
            System.out.println("Original byte " + i + " " + bytes[i]);
        }
        float[] test = toDouble(bytes);

        System.out.println("Converting to float------------------");
        for (int i = 0; i < test.length; i++) {
            System.out.println(test[i]);
        }

        System.out.println("Converting to byte------------------");
        bytes = toByte(test);
    }

    public static byte[] toByte(float[] data) {
        byte[] bytes = new byte[data.length * 2];
        ByteBuffer bb;
        int k = 0;
        for (int i = 0; i < data.length; i++) {
            float v = data[i];
            bb = ByteBuffer.wrap(bytes, k, 2);
            bb.order(ByteOrder.LITTLE_ENDIAN);
            
            v *= 32768.0;
            short value = (short) v;
            bb.putShort((short) (value & 0xffff));
           
            // Swap the bytes, since they are reversed
            byte temp = bytes[k];
            bytes[k] = bytes[k+1];
            bytes[k+1] = temp;
            System.out.println(bytes[k] + ", " + bytes[k+1]);
            k+=2;
        }
        return bytes;
    }

    public static float[] toDouble(byte[] data) {
        // where data is the byte array.
        ByteBuffer byteBuffer = ByteBuffer.wrap(data);
        // make sure that the data is in Little endian order.
        byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
        // every double will represent 2 bytes (16bit audio sample)
        // so the double[] is half length of byte[]
        float[] doubleData = new float[data.length / 2];
        float[] dd = new float[data.length / 2];
        int i = 0;
        int remaining = byteBuffer.remaining();

        while (byteBuffer.remaining() > 1) {
            // read shorts (16bits) and cast them to doubles
            short t = byteBuffer.getShort();
            doubleData[i] = t;
            doubleData[i] /= 32768.0;
            i++;
        }
        return doubleData;
    }
}
